<?php
namespace ImiApp\ApiServer\Controller;

use Imi\Controller\HttpController;
use Imi\Db\Db;
use Imi\Server\Route\Annotation\Action;
use Imi\Server\Route\Annotation\Controller;

/**
 * @Controller("/db/")
 */
class DbController extends HttpController
{
    /**
     * @Action
     *
     * @param string $a
     * @return void
     */
    public function create($a)
    {
        $db = Db::getInstance();
        $statement = $db->prepare('insert into tb_test(a) values(:a)');
        $statement->execute([
            ':a'    =>  $a,
        ]);
        return [
            'id'    =>  $statement->lastInsertId(),
        ];
    }

    /**
     * @Action
     *
     * @param int $id
     * @param string $a
     * @return void
     */
    public function update($id, $a)
    {
        $db = Db::getInstance();
        $statement = $db->prepare('update tb_test set a=:a where id=:id');
        $statement->execute([
            ':id'   =>  $id,
            ':a'    =>  $a,
        ]);
        return [
            'rowCount'    =>  $statement->rowCount(),
        ];
    }

    /**
     * @Action
     *
     * @param int $id
     * @return void
     */
    public function get($id)
    {
        $db = Db::getInstance();
        $statement = $db->prepare('select * from tb_test where id=:id');
        $statement->execute([
            ':id'   =>  $id,
        ]);
        return [
            'data'    =>  $statement->fetch(),
        ];
    }

    /**
     * @Action
     *
     * @return void
     */
    public function query()
    {
        $db = Db::getInstance();
        $statement = $db->query('select * from tb_test');
        return [
            'list'  =>  $statement->fetchAll(),
        ];
    }

    /**
     * @Action
     *
     * @param int $id
     * @return void
     */
    public function delete($id)
    {
        $db = Db::getInstance();
        $statement = $db->prepare('delete from tb_test where id=:id');
        $statement->execute([
            ':id'   =>  $id,
        ]);
        return [
            'rowCount'    =>  $statement->rowCount(),
        ];
    }

}
